/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.teaching.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.teaching.entity.Question;
import com.thinkgem.jeesite.modules.teaching.dao.QuestionDao;
import com.thinkgem.jeesite.modules.teaching.entity.Answer;
import com.thinkgem.jeesite.modules.teaching.dao.AnswerDao;

/**
 * 题目管理Service
 * @author 王卫党
 * @version 2018-01-28
 */
@Service
@Transactional(readOnly = true)
public class QuestionService extends CrudService<QuestionDao, Question> {

	@Autowired
	private AnswerDao answerDao;
	
	public Question get(String id) {
		Question question = super.get(id);
		question.setAnswerList(answerDao.findList(new Answer(question)));
		return question;
	}
	
	public List<Question> findList(Question question) {
		return super.findList(question);
	}
	
	public Page<Question> findPage(Page<Question> page, Question question) {
        Page<Question> pageResult = super.findPage(page, question);
        List<Question> questions = pageResult.getList();
        for (Question questionResult : questions) {
            questionResult.setAnswerList(answerDao.findList(new Answer(questionResult)));
        }
        return pageResult;
	}
	
	@Transactional(readOnly = false)
	public void save(Question question) {
		super.save(question);
		for (Answer answer : question.getAnswerList()){
			if (answer.getId() == null){
				continue;
			}
			if (Answer.DEL_FLAG_NORMAL.equals(answer.getDelFlag())){
				if (StringUtils.isBlank(answer.getId())){
					answer.setQuestionId(question.getId());
					answer.preInsert();
					answerDao.insert(answer);
				}else{
					answer.preUpdate();
					answerDao.update(answer);
				}
			}else{
				answerDao.delete(answer);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Question question) {
		super.delete(question);
		answerDao.delete(new Answer(question));
	}
	
}